﻿using Dapper;
using Management.Systeam.Domaina;
using Management.Systeam.ErrorCode;
using Management.Systeam.Infrastructure.Implement;
using Management.Systeam.Infrastructure.Interface;
using Management.Systeam.Read.Apis.Application.Command.Rolees;
using MediatR;
using System.Text;

namespace Management.Systeam.Read.Apis.Application.CommandHandler.Rolees
{
    public class ShowRoleCommandHandler : IRequestHandler<ShowRoleCommand, ApiPeaging<ApiResult<List<Role>>>>
    {
        IBaseRepository<Users> Users;
        IBaseRepository<RoleUser> RoleUser;
        IBaseRepository<Role> Role;
        DatabaseContext db;
        public ShowRoleCommandHandler(IBaseRepository<Users> Users, IBaseRepository<RoleUser> RoleUser, IBaseRepository<Role> Role, DatabaseContext db)
        {
            this.Users = Users;
            this.RoleUser = RoleUser;
            this.Role = Role;
            this.db = db;
        }

        public async Task<ApiPeaging<ApiResult<List<Role>>>> Handle(ShowRoleCommand request, CancellationToken cancellationToken)
        {

         
            StringBuilder sb = new StringBuilder();
            sb.Append("SELECT * FROM Role");
            sb.Append(" WHERE IsDel LIKE '%" + 0 + "%'");

            if (request.Role_Name != null)
            {
                sb.Append(" AND Role_Name LIKE '%" + request.Role_Name+"%'");
            }
            if (request.Role_Content != null)
            {
                sb.Append(" AND Role_Content LIKE '%" + request.Role_Content + "%'");
            }
            var paramet = new
            {
                Role_Name = request.Role_Name,
                Role_Content = request.Role_Content,
                PageSize = request.PageSize,
                offset = (request.PageIndex - 1) * request.PageSize
            };
            var qtlist = await db.DapperConnection.QueryAsync<Role>(sb.ToString(), paramet);
            int total = qtlist.Count();
            sb.Append(" ORDER BY Role_Id DESC LIMIT @PageSize OFFSET @offset");
            var pageData = await db.DapperConnection.QueryAsync<Role>(sb.ToString(), paramet);
            int totalPage = (int)Math.Ceiling(total / (double)request.PageSize);
    
            return new ApiPeaging<ApiResult<List<Role>>>
            {
                Total = total,
                TotalPage = totalPage,
                Data = new ApiResult<List<Role>> 
                {
                    Code = ApiEnum.success,
                    Message = "查询成功",
                    Data = pageData.ToList()
                }
            };
        }
    }
}
